package cn.mesmile.thread;

/**
 *  CPU多级缓存中的【空间局部性】  一个缓存行 64byte
 * @author zb
 */
public class TwoDimensionalArraySum {

    private static final int RUNS = 100;
    // 列
    private static final int DIMENSION_1 = 1024 * 1024;
    // 行
    private static final int DIMENSION_2 = 6;
    private static long[][] longs;

    public static void main(String[] args) throws Exception {
        /*
         * 初始化数组
         *  列：1024*1024
         *  行：6
         */
        longs = new long[DIMENSION_1][];
        for (int i = 0; i < DIMENSION_1; i++) {
            longs[i] = new long[DIMENSION_2];
            for (int j = 0; j < DIMENSION_2; j++) {
                longs[i][j] = 1L;
            }
        }
        System.out.println("Array初始化完毕....");

        long sum = 0L;
        long start = System.currentTimeMillis();
        for (int r = 0; r < RUNS; r++) {
            for (int j = 0; j < DIMENSION_2; j++) {//6
                for (int i = 0; i < DIMENSION_1; i++) {//1024*1024
                    // 一列一列的加
                    sum += longs[i][j];
                }
            }
        }
        // spend time2:5805
        System.out.println("spend time2:" + (System.currentTimeMillis() - start));
        System.out.println("sum2:" + sum);

        sum = 0L;
        start = System.currentTimeMillis();
        for (int r = 0; r < RUNS; r++) {
            for (int i = 0; i < DIMENSION_1; i++) {//DIMENSION_1=1024*1024
                for (int j = 0; j < DIMENSION_2; j++) {//6
                    // 一行一行的加 【空间局部性】：会一次就读取一行，一个缓存行64byte，可以读取8个Long（8byte）类型数据
                    sum += longs[i][j];
                }
            }
        }
        // spend time1:1118
        System.out.println("spend time1:" + (System.currentTimeMillis() - start));
        System.out.println("sum1:" + sum);
    }
}